import { observable, action, toJS } from 'mobx';
import { message } from 'antd';
import Apis from '../apis/cowork';
import { WeaTableNew, WeaLogView, WeaForm } from 'comsMobx';

const { TableStore } = WeaTableNew;
const { LogStore } = WeaLogView;
import { WeaLocaleProvider } from 'ecCom';
import coworkMainStore from './CoworkStore';

const getLabel = WeaLocaleProvider.getLabel;

const participationTab = () => [
  {
    title: getLabel(382638, '参与范围'),
    groupid: 'shareScope',
    viewcondition: 1,
  },
  {
    title: getLabel('524322', '默认参与人'),
    groupid: 'defaultjoin',
    viewcondition: '3',
  },
];

const defaultTab = () => [
  {
    title: getLabel(382637, '协作信息'),
    groupid: 'msg',
    viewcondition: 0,
  },
  ...participationTab(),
  {
    title: getLabel(382659, '已退出人员'),
    groupid: 'quit',
    viewcondition: 2,
  },
];

export default class NewCoworkStore {
  @observable createForm = new WeaForm();
  @observable createTable = new TableStore();
  @observable quitTable = new TableStore();
  @observable defalutJoinerTable = new TableStore();
  @observable logStore = new LogStore();
  @observable newCoworkStatus = {
    showNewCowork: false,
    createOrEdit: 0,
    selectedKey: 0,
    createCondition: [],
    createList: [],
    authCondition: [],
    showAuth: false,
    saveLoading: false,
    selectValue: '', // 下拉框的值
    defaultSelectValue: '',
    dateValue: '', // datePicker的值
    associateList: [], // 版块绑定的一些详细字段通过key关联 -- 控制允许匿名 0：不显示 1：显示
    editId: '',

    itemsVO: {}, // 编辑时候的信息
    accessoryPath: '', // 附件的上传路径
    editCoworkInfo: false, // 判断是否协作详情点解编辑进入

    showNewPlate: false, // 新建版块
  };

  @observable status = {
    targetId: '',
    logType: '24', // 日志相关参数
    logSmallType: '20',
  };

  // 富文本下按钮配置项
  @observable config = {
    appStatus: {},
    appData: [],
    appDataByType: new Map(),
  };

  @observable loaded = false; // 一步加载
  @observable pageState = '';

  topTab = defaultTab();
  topTitle = '';

  @action setStoreState = (params = {}) => {
    Object.keys(params).forEach((key) => {
      this[key] = params[key];
    });
  };

  @action
  doInit = (params = {}) => {
    // 回调是编辑的时候带出数据，更新form用
    this.getNewMyCoworkTypeList();
    this.coworkAddCondition();
    // 这个方法是为了抛出去的dialog初始化富文本下方按钮信息，原来的是在协作主页处初始化，不合理。
    this.getCoworkAppStatus(); // 富文本下方按钮
    if (JSON.stringify(params) == '{}') {
      // 外部模块调用新建才有参数，本模块无，则无需取默认数据
    } else {
      this.getCoworkAppData(params); // 富文本下方按钮默认数据
    }
  };

  // 获取协作富文本下方按钮
  getCoworkAppStatus = () => {
    Apis.getCoworkAppStatus().then((result) => {
      this.config.appStatus = result.appStatus;
    });
  };

  // 获取协作富文本下方按钮默认数据
  getCoworkAppData = (params) => {
    let relatedType = params.relatedType;
    Apis.getCoworkAppData(params).then((result) => {
      this.config.appData = result.dataList;
      this.config.appDataByType.set(relatedType, result.dataList);
    });
  };

  @action setCreateState = (params = {}) => {
    let newCoworkStatus = { ...this.newCoworkStatus };
    Object.keys(params).forEach((key) => {
      newCoworkStatus[key] = params[key];
    });
    this.newCoworkStatus = newCoworkStatus;
  };

  doCreateFormInit = (condition) => {
    this.newCoworkStatus = {
      ...this.newCoworkStatus,
      itemsVO: {},
      accessoryPath: '',
      selectValue: this.newCoworkStatus.defaultSelectValue, // 初始化的时候form默认选中的 版块数据
      dateValue: '',
      editCoworkInfo: false,
      selectedKey: 0,
    };
    this.createForm = new WeaForm();
    this.createForm.initFormFields(
      condition || toJS(this.newCoworkStatus.createCondition),
    );
    window.e9ChangedFormFieldKey = 'sjldkvokddkaq';
  };

  // 协作新建condition
  coworkAddCondition = () => {
    Apis.coworkAddCondition().then((result) => {
      this.doCreateFormInit(result.condition);
      const selectValue =
        result.condition &&
        result.condition[0].items[1].options &&
        result.condition[0].items[1].options.length > 0 &&
        result.condition[0].items[1].options.filter(
          v => v.selected == true,
        )[0].key;
      this.newCoworkStatus = {
        ...this.newCoworkStatus,
        createCondition: result.condition,
        selectValue,
        defaultSelectValue: selectValue, // 从form数据这里取值，保证新建的初始值，避免编辑的时候出现问题
      };
      this.getAccessoryPath(selectValue);
    });
  };

  // 获取协作附件目录
  getAccessoryPath = (typeId) => {
    // const id = this.createForm.getFormParams().typeId || '';
    // if (typeId != id) {
    Apis.getCoworkAccessory({ typeId }).then((result) => {
      if (result.status == '1') {
        this.newCoworkStatus.accessoryPath = result;
        this.newCoworkStatus.itemsVO = {
          ...this.newCoworkStatus.itemsVO,
          relatedaccList: [],
        };
      } else {
        message.error(
          getLabel(187, '读取协作附件失败, msg:', 'error') + result.msg,
        );
      }
    });
    // }
  };

  // 协作参与范围-参与人列表
  coworkShareList = (params, getFirstPage = false) => {
    Apis.coworkShareList(params).then((result) => {
      getFirstPage
        ? this.createTable.getDatas(result.sessionkey, 1)
        : this.createTable.getDatas(result.sessionkey);
    });
  };

  // 新建协作版块下拉框
  getNewMyCoworkTypeList = () => {
    Apis.getNewMyCoworkTypeList().then((result) => {
      let list = [];
      this.newCoworkStatus.associateList = result.option;
      result.option &&
        result.option.map((v) => {
          list.push({
            showname: v.showname,
            key: v.key,
          });
        });

      // 协作负责人不是版块创建人的时候，编辑协作时，版块框显示是空白的
      // if(""!=itemsVO&&undefined!=itemsVO){
      //   list.push({
      //     showname: itemsVO.coworkBelongToTypeName,
      //     key: itemsVO.typeid,
      //   })
      // }
      this.newCoworkStatus.createList = list;
    });
  };

  // 协作-新建协作参与人者conditions（仅前台参与人使用）
  getWeaAuthConditions = () => {
    Apis.getWeaAuthConditions().then((result) => {
      this.newCoworkStatus.authCondition = result.conditioninfo;
    });
  };

  @action onCheckPrincipal = params =>
    Apis.judgeCoworkAuthorityChange(params);

  // 协作-协作交流-保存/编辑协作
  saveorupdateCoworkItemVo = (params, type, callback, needDelay = false) => {
    if (type == 'create') {
      this.newCoworkStatus.saveLoading = true;
    }
    if (type == 'saveSet') {
      this.newCoworkStatus.saveSetLoading = true;
    }
    Apis.saveorupdateItemVo(params).then((result) => {
      this.newCoworkStatus.saveLoading = false;
      this.newCoworkStatus.saveSetLoading = false;
      if (result.flag) {
        if (type == 'create') {
          // 保存
          this.newCoworkStatus = {
            ...this.newCoworkStatus,
            itemsVO: {},
            showNewCowork: false,
          };
          this.doCreateFormInit();
          message.success(`${getLabel(83885, '操作成功！')}`);
        }
        if (type == 'editSave') {
          // 保存内容并跳转
          message.success(`${getLabel(83885, '操作成功！')}`);
        }
        if (type == 'saveSet') {
          // 保存并进入详细设置
          this.newCoworkStatus = {
            ...this.newCoworkStatus,
            itemsVO: { ...result.coworkItemVoMap.itemsVO },
            createOrEdit: 1,
            editId: result.coworkItemVoMap.itemsVO.id,
          };
          this.coworkShareList({ coworkId: result.coworkItemVoMap.itemsVO.id });
        }
        if (callback && !needDelay) callback(); // 外部调用的时候的回调处理
        coworkMainStore.reloadCowork('', needDelay ? callback : ''); // 保存成功重新加载接口得到新的编辑的数据
        coworkMainStore.reloadLeftList(); // 保存成功刷新左侧数
        coworkMainStore.reloadRecordList();
      } else {
        message.error(`${getLabel(4715, '操作失败')}`);
      }
    });
  };

  // 协作-协作交流-保存/编辑协作参与人信息(只保存协作参与人信息，基本信息分开来保存)
  saveorupdateCoworkShare = (params) => {
    Apis.saveorupdateCoworkShare(params).then((result) => {
      this.newCoworkStatus.showAuth = false;
      if (result.status == 1) {
        this.coworkShareList({ coworkId: this.newCoworkStatus.editId });
        coworkMainStore.reloadLeftList(); // 保存成功刷新左侧数
      } else {
        message.error(`${getLabel(4715, '操作失败')}`);
      }
    });
  };

  @action doEditInit = (page = 0, params) => {
    const itemsVO = toJS(coworkMainStore.content.cowork.itemsVO);
    switch (page) {
      case 1:
        this.pageState = '1';
        this.topTitle = getLabel(83210, '参与条件');
        this.topTab = participationTab();
        this.setCreateState({ selectedKey: page });
        this.coworkShareList({ coworkId: itemsVO.id, ...params });
        break;
      case 2:
        break;
      default: {
        this.pageState = '';
        this.topTitle = getLabel(83251, '编辑协作');
        this.topTab = defaultTab();
        params = {
          id: itemsVO.id,
          type: 'edit',
          ...params,
        };
        Apis.coworkAddCondition(params).then(
          action('fetchSuccess', (res) => {
            this.createForm = new WeaForm();
            const condition = res.condition || toJS(this.newCoworkStatus.createCondition);
            this.createForm.initFormFields(condition);
            this.newCoworkStatus = {
              ...this.newCoworkStatus,
              createCondition: res.condition,
              createList: (condition[0] && condition[0].items && condition[0].items[1] && condition[0].items[1].options) || [],
            };
          }),
        );
        const enddate =
          itemsVO && itemsVO.enddate && itemsVO.enddate.split(' ').join('');
        const endtime =
          itemsVO && itemsVO.endtime && itemsVO.endtime.split(' ').join('');
        // 按照datePicker需要的数据格式处理返回的数据
        const endDate =
          enddate.length !== 0 || endtime.length !== 0
            ? `${enddate.replace('"', '')} ${endtime.replace('"', '')}`
            : '';
        this.setCreateState({
          dateValue: endDate, // datePicker值更新
          selectValue: itemsVO.typeid, // 下拉框值更新
        });
      }
    }
    this.setCreateState({
      showNewCowork: true,
      createOrEdit: 1,
      editCoworkInfo: true,
      editId: itemsVO.id,
    });
  };

  setLoaded = (bool) => {
    this.loaded = bool;
  };

  /* 编辑协作---已退出人员Tab页请求 */
  getQuitList = (isInit = false) => {
    const editId = this.newCoworkStatus.editId;
    let params = { coworkId: editId };
    Apis.getQuitList(params).then((res) => {
      isInit
        ? this.quitTable.getDatas(res.sessionkey, 1)
        : this.quitTable.getDatas(res.sessionkey);
    });
  };

  /* 重新加入协作 */
  reJoinCoworkQuiter = (params, callback) => {
    const itemsVO = toJS(coworkMainStore.content.cowork.itemsVO);
    params = { coworkId: itemsVO.id, ...params };
    Apis.reJoinCoworkQuiter(params).then((res) => {
      if (res.flag) {
        this.getQuitList();
        if (callback) callback();
      } else {
        message.error(getLabel(4715, '操作失败'));
      }
    });
  };

  @action getDefaultJoinList = (params, initPage = true) => {
    Apis.getCoworkTypeShareList(params).then((res) => {
      initPage
        ? this.defalutJoinerTable.getDatas(res.sessionkey, 1)
        : this.defalutJoinerTable.getDatas(res.sessionkey);
    });
  };
}
